package com.liyuxiang.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liyuxiang.domain.LoginUser;
import com.liyuxiang.mapper.MenuMapper;
import com.liyuxiang.mapper.UserMapper;
import com.liyuxiang.pojo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 创建我们自己的service
 * 目的是为了改变UserDetailsService默认从内存中查询用户和密码的策略
 * 这里是查询数据库
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName,username));
        //如果根据用户名查出来为空，代表该用户不存在 抛出异常
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }

        //TODO 查询对应权限信息
        List<String> authorities = menuMapper.selectPermsByUserId(user.getId());
//        List<String> authorities = new ArrayList<>(Arrays.asList("test","admin"));

        //数据封装UserDetails并返回
        System.out.println(user);
        System.out.println(username);

        return new LoginUser(user,authorities);
    }
}
